import json
import os
from urllib.parse import urlencode

from playwright.sync_api import Playwright, sync_playwright, expect
import subprocess
from playwright.async_api import async_playwright

#输入Chrome浏览器所在路径
chrome_path = r'"C:\Program Files\Google\Chrome\Application\chrome.exe"'
debugging_port = "--remote-debugging-port=9222"

command = f'{chrome_path} {debugging_port} --user-data-dir="C:\chrome-debug"'
subprocess.Popen(command, shell=True)

def run(playwright: Playwright) -> None:
    browser = playwright.chromium.connect_over_cdp(("http://localhost:9222"))
    context = browser.contexts[0]
    page = context.new_page()
    page.goto("https://www.lazada.com.ph/")
    handle_captcha_manual(page)
    for current_page in range(1, 3 + 2):
        params = {
            'ajax': "true",
            'page': current_page,
            'q': 'Portable Speakers',
            'src': 'all_channel',
            'service': 'all_channel',
            'isFirstRequest': "true"
        }
        url = "https://www.lazada.com.ph/catalog/?" + urlencode(params)
        new_page=context.new_page()
        new_page.goto(url)

def handle_captcha_manual( page):
    try:
        page.wait_for_selector('.captcha-container', timeout=10000)
        # self.logger.warning("请手动完成验证码，按Enter继续...")
        # input("按Enter继续...")
    except:
        return

if __name__ == '__main__':
    from config import PROJECT_ROOT
    from util.JSONTreeUtil import JSONTreeUtil
    category_data_path = os.path.join(PROJECT_ROOT, "category", "lazada.json")
    with open(category_data_path, "r", encoding="utf-8") as p:
        categories = json.load(p)
        category_list = JSONTreeUtil.to_flat_list(categories,name_key='categoryNameZh', children_key='level2TabList')
        # print(category_list)
    for category in category_list:
        if category['path'].find("运动与生活方式") != -1:
            # print(f'{category["categoryNameZh"]}: {category["categoryUrl"]}')
            if category.get("categoryUrl") is not None:
                # print(f'{category["path"]}: {category["categoryUrl"]}')
                with sync_playwright() as p:
                    browser = p.chromium.connect_over_cdp(("http://localhost:9222"))
                    context = browser.contexts[0]
                    page = context.new_page()


                    def on_url_change(url):
                        print(f"地址栏变化为: {url}")

                    page.on("framenavigated", lambda frame: on_url_change(frame.url))

                    page.goto(f"https:{category['categoryUrl']}")
                    page.close()

            else:
                print(f'{category["path"]}: {category["path"]}')
                continue

